<!--
  智慧社区管理系统 - 权限表单弹窗
  @author Wu.Liang
  @date 2024-01-01
  @updated 2024-12-21 - 完善权限表单弹窗功能
-->
<template>
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑权限' : '新增权限'"
        width="700px"
        :close-on-click-modal="false"
        @close="handleClose"
    >
        <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-width="120px"
            class="permission-form"
        >
            <el-form-item label="权限名称" prop="permissionName">
                <el-input
                    v-model="formData.permissionName"
                    placeholder="请输入权限名称"
                    maxlength="50"
                    show-word-limit
                    clearable
                />
            </el-form-item>
            
            <el-form-item label="权限编码" prop="permissionCode">
                <el-input
                    v-model="formData.permissionCode"
                    placeholder="请输入权限编码（如：user:list）"
                    maxlength="100"
                    show-word-limit
                    clearable
                />
                <div class="form-tip">
                    权限编码格式：模块:功能，如：user:list、user:create、user:update
                </div>
            </el-form-item>
            
            <el-form-item label="权限类型" prop="type">
                <el-radio-group v-model="formData.type" disabled>
                    <el-radio :value="1">
                        <el-icon><Menu /></el-icon>
                        菜单权限
                    </el-radio>
                </el-radio-group>
                <div class="form-tip">
                    <el-icon><InfoFilled /></el-icon>
                    <span>权限系统已简化，仅支持菜单级权限控制</span>
                </div>
            </el-form-item>
            
            <el-form-item label="父权限" prop="parentId">
                <el-tree-select
                    v-model="formData.parentId"
                    :data="permissionTreeOptions"
                    :props="treeProps"
                    placeholder="请选择父权限（可选）"
                    clearable
                    style="width: 100%"
                    :render-after-expand="false"
                >
                    <template #default="{ node, data }">
                        <div class="tree-select-node">
                            <el-icon class="node-icon" :class="getNodeIconClass(data.type)">
                                <component :is="getNodeIcon(data.type)" />
                            </el-icon>
                            <span class="node-label">{{ data.permissionName }}</span>
                            <el-tag 
                                v-if="data.type" 
                                size="small" 
                                :type="getPermissionTypeTag(data.type)"
                                class="node-type"
                            >
                                {{ getPermissionTypeText(data.type) }}
                            </el-tag>
                        </div>
                    </template>
                </el-tree-select>
            </el-form-item>
            
            <el-form-item label="权限路径" prop="permissionPath" v-if="formData.type === 1">
                <el-input
                    v-model="formData.permissionPath"
                    placeholder="请输入权限路径（如：/user/list）"
                    maxlength="200"
                    show-word-limit
                    clearable
                />
                <div class="form-tip">
                    菜单权限需要设置路径，用于路由跳转
                </div>
            </el-form-item>
            
            <el-form-item label="权限URL" prop="permissionUrl" v-if="formData.type === 3">
                <el-input
                    v-model="formData.permissionUrl"
                    placeholder="请输入API接口URL（如：/api/user/list）"
                    maxlength="200"
                    show-word-limit
                    clearable
                />
                <div class="form-tip">
                    API权限需要设置接口URL，用于权限验证
                </div>
            </el-form-item>
            
            <el-form-item label="权限图标" prop="icon" v-if="formData.type === 1">
                <el-input
                    v-model="formData.icon"
                    placeholder="请输入图标名称（如：User、Setting）"
                    maxlength="50"
                    clearable
                />
                <div class="form-tip">
                    菜单权限可以设置图标，使用Element Plus图标名称
                </div>
            </el-form-item>
            
            <el-form-item label="排序号" prop="sortOrder">
                <el-input-number
                    v-model="formData.sortOrder"
                    :min="0"
                    :max="999"
                    placeholder="请输入排序号"
                    style="width: 100%"
                />
                <div class="form-tip">
                    数字越小排序越靠前，默认为0
                </div>
            </el-form-item>
            
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="formData.status">
                    <el-radio :value="1">启用</el-radio>
                    <el-radio :value="0">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
            
            <el-form-item label="权限描述" prop="description">
                <el-input
                    v-model="formData.description"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入权限描述"
                    maxlength="255"
                    show-word-limit
                />
            </el-form-item>
            
            <el-form-item label="备注" prop="remark">
                <el-input
                    v-model="formData.remark"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入备注信息"
                    maxlength="500"
                    show-word-limit
                />
            </el-form-item>
        </el-form>
        
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
                    {{ isEdit ? '更新' : '创建' }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { type FormInstance, type FormRules } from 'element-plus'
import { showSuccess, showError } from '@/utils/message'
import { 
    Menu, 
    Operation, 
    Key, 
    Setting
} from '@element-plus/icons-vue'
import type { PermissionTree } from '@/api/role'
import { getPermissionTree } from '@/api/role'

// Props
interface Props {
    modelValue: boolean
    permissionData?: PermissionTree | null
    parentPermission?: PermissionTree | null
}

const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    permissionData: null,
    parentPermission: null
})

// Emits
const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    'success': []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const permissionTreeOptions = ref<PermissionTree[]>([])

// 表单数据
const formData = reactive({
    permissionName: '',
    permissionCode: '',
    permissionType: 1, // 固定为菜单权限类型
    parentId: undefined as number | undefined,
    permissionPath: '',
    permissionUrl: '',
    icon: '',
    sortOrder: 0,
    status: 0,
    description: '',
    remark: ''
})

// 表单验证规则
const formRules: FormRules = {
    permissionName: [
        { required: true, message: '请输入权限名称', trigger: 'blur' },
        { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    permissionCode: [
        { required: true, message: '请输入权限编码', trigger: 'blur' },
        { min: 2, max: 100, message: '权限编码长度在 2 到 100 个字符', trigger: 'blur' },
        { pattern: /^[a-z][a-z0-9_]*:menu$/, message: '权限编码格式：模块:menu，如：user:menu', trigger: 'blur' }
    ],
    permissionType: [
        { required: true, message: '请选择权限类型', trigger: 'change' }
    ],
    permissionPath: [
        { pattern: /^\/[a-z0-9\/-]*$/, message: '权限路径格式：/user/list', trigger: 'blur' }
    ],
    permissionUrl: [
        { pattern: /^\/api\/[a-z0-9\/-]*$/, message: 'API URL格式：/api/user/list', trigger: 'blur' }
    ],
    sortOrder: [
        { type: 'number', min: 0, max: 999, message: '排序号必须在 0-999 之间', trigger: 'blur' }
    ],
    description: [
        { max: 255, message: '权限描述长度不能超过 255 个字符', trigger: 'blur' }
    ],
    remark: [
        { max: 500, message: '备注长度不能超过 500 个字符', trigger: 'blur' }
    ]
}

// 树形配置
const treeProps = {
    children: 'children',
    label: 'permissionName',
    value: 'id'
}

// 计算属性
const dialogVisible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.permissionData?.id)

// 获取权限树选项
const fetchPermissionTreeOptions = async () => {
    try {
        const response = await getPermissionTree()
        permissionTreeOptions.value = response.data
    } catch (error: any) {
        showError(`获取权限树失败: ${error.message}`)
    }
}

// 监听弹窗显示
watch(() => props.modelValue, (visible) => {
    if (visible) {
        fetchPermissionTreeOptions()
    }
})

// 监听权限数据变化
watch(() => props.permissionData, (newPermissionData) => {
    if (newPermissionData) {
        // 编辑模式，填充表单数据
        Object.assign(formData, {
            permissionName: newPermissionData.permissionName,
            permissionCode: newPermissionData.permissionCode,
            permissionType: newPermissionData.permissionType,
            parentId: newPermissionData.parentId,
            permissionPath: newPermissionData.permissionPath || '',
            permissionUrl: newPermissionData.permissionUrl || '',
            icon: newPermissionData.icon || '',
            sortOrder: newPermissionData.sortOrder,
            status: newPermissionData.status,
            description: newPermissionData.description || '',
            remark: newPermissionData.remark || ''
        })
    } else {
        // 新增模式，重置表单数据
        resetForm()
    }
}, { immediate: true })

// 监听父权限变化
watch(() => props.parentPermission, (newParentPermission) => {
    if (newParentPermission) {
        formData.parentId = newParentPermission.id
    }
}, { immediate: true })

// 重置表单
const resetForm = () => {
    Object.assign(formData, {
        permissionName: '',
        permissionCode: '',
        permissionType: 1,
        parentId: props.parentPermission?.id,
        permissionPath: '',
        permissionUrl: '',
        icon: '',
        sortOrder: 0,
        status: 0,
        description: '',
        remark: ''
    })
    
    nextTick(() => {
        formRef.value?.clearValidate()
    })
}

// 关闭弹窗
const handleClose = () => {
    dialogVisible.value = false
    resetForm()
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        submitLoading.value = true
        
        // TODO: 调用创建或更新API
        if (isEdit.value) {
            showSuccess('权限更新成功')
        } else {
            showSuccess('权限创建成功')
        }
        
        emit('success')
        handleClose()
    } catch (error: any) {
        if (error !== 'cancel') {
            showError(`操作失败: ${error.message}`)
        }
    } finally {
        submitLoading.value = false
    }
}

// 工具函数
const getNodeIcon = (type: number) => {
    switch (type) {
        case 1: return Menu // 菜单
        default: return Setting
    }
}

const getNodeIconClass = (type: number) => {
    switch (type) {
        case 1: return 'icon-menu'
        default: return 'icon-default'
    }
}

const getPermissionTypeTag = (type: number) => {
    switch (type) {
        case 1: return 'primary'
        default: return 'info'
    }
}

const getPermissionTypeText = (type: number) => {
    switch (type) {
        case 1: return '菜单'
        default: return '未知'
    }
}
</script>

<style lang="scss" scoped>
.permission-form {
    .form-tip {
        margin-top: 4px;
        font-size: 12px;
        color: #909399;
        line-height: 1.4;
    }

    .el-radio-group {
        .el-radio {
            display: flex;
            align-items: center;
            gap: 4px;
            margin-right: 20px;

            .el-icon {
                font-size: 16px;
            }
        }
    }
}

.tree-select-node {
    display: flex;
    align-items: center;
    gap: 8px;
    width: 100%;

    .node-icon {
        font-size: 14px;
        
        &.icon-menu {
            color: #409eff;
        }
        
        &.icon-button {
            color: #67c23a;
        }
        
        &.icon-api {
            color: #e6a23c;
        }
        
        &.icon-default {
            color: #909399;
        }
    }

    .node-label {
        flex: 1;
        font-size: 14px;
        color: #303133;
    }

    .node-type {
        flex-shrink: 0;
    }
}

.dialog-footer {
    text-align: right;
    padding-top: 20px;
    border-top: 1px solid #f0f0f0;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

:deep(.el-input-number) {
    .el-input__wrapper {
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        
        &:hover {
            box-shadow: 0 0 0 1px #c0c4cc inset;
        }
        
        &.is-focus {
            box-shadow: 0 0 0 1px #409eff inset;
        }
    }
}
</style> 